package com.coocaa.upgrade;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageParser;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LiteHandlerThread;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.liteupgrade.LiteUpgradeKernel;
import com.coocaa.x.service.liteupgrade.aidl.UpgradeInfo;
import com.coocaa.x.service.liteupgrade.aidl.UpgradeParams;
import com.coocaa.x.uipackage.dialog.UpgradeDialog;
import com.skyworth.framework.skysdk.android.SdCardChecker;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.skyworth.webSDK.webservice.tcappstore.StoreApkInfo;
import com.tianci.appstore.R;
import com.tianci.appstore.ui.widget.TipToast;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by lu on 15-6-19.
 */
public class UpgradeKernel extends LiteUpgradeKernel {
    private UpgradeInfo info = new UpgradeInfo();
    private String url = "";
    private UpgradeDialog upgradeDialog = null;

    private boolean can_show_dialog = false;

    private static final int SHOW_DIALOG_TYPE_ALL = 0;
    private static final int SHOW_DIALOG_TYPE_ONLY_HAS_UPDATE = 1;
    private int show_dialog_type = SHOW_DIALOG_TYPE_ALL;

    private void _getUpgradeInfo(String device_channel) {
//        if (false) {
        StoreApkInfo apkinfo = null;
        try {
            apkinfo = CoocaaApplication.getCoocaaWebService().getAppStoreService()
                    .getStoreApkInfo(device_channel);
            if (apkinfo != null) {
                String j = JSONObject.toJSONString(apkinfo);
                LogUtils.d("upgrade", "apkinfo:" + j);
                info.versionCode = Integer.valueOf(apkinfo.verCode);
                try {
                    if (info.versionCode > mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode) {
                        info.hasUpgrade = true;
                        info.versionName = apkinfo.verName;
                        info.name = apkinfo.appName;
                        info.size = 0;
                        info.upgradeLog = apkinfo.updateInfo;
                        info.md5 = apkinfo.md5;
                        url = apkinfo.apkDownUrl;
                    } else {
                        info.hasUpgrade = false;
                        url = "";
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    info.hasUpgrade = false;
                    url = "";
                }
            } else {
                info.hasUpgrade = false;
                url = "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogAPIForAppStore.reportInterfaceError("获取商城APK信息", Android.throwable2String(e));
            info.hasUpgrade = false;
            url = "";
        }
//        }

//        test();
    }

    private void test() {
        info.hasUpgrade = true;
        info.versionCode = 999999999;
        info.versionName = "2.3";
        info.name = "测试升级app";
        info.size = 0;
        info.upgradeLog = "測試升級app日誌:\n1、zcvzxczxczxczczx3123123\n2、支持v131312312字吃頓飯犬瘟熱1 12全文啊";
        info.md5 = "975be188eed135bd035ea6854181e5b8";
//"http://dldir1.qq.com/qqfile/qq/QQ7.9/16621/QQ7.9.exe"
        //"https://qd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk"
        url = "http://mbdapp.iqiyi.com/j/ap/qiyi.196.apk";
    }

    @Override
    public void prepare(final UpgradeParams params) {
        String value = params.params.get("show_dialog");
        if (value == null || !value.equals("only_has_update"))
            show_dialog_type = SHOW_DIALOG_TYPE_ALL;
        else
            show_dialog_type = SHOW_DIALOG_TYPE_ONLY_HAS_UPDATE;
        LogUtils.d("upgrade", "show_dialog_type:" + show_dialog_type + " value:" + value);

//        LiteHandlerThread.postOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                if (upgradeDialog == null) {
//                    upgradeDialog = new UpgradeDialog(mContext);
//                    upgradeDialog.setOnUpdateEventListener(new UpgradeDialog.OnUpgradeDialogEventListener() {
//                        @Override
//                        public void onClickCallBack(String apkFilePath) {
//                            if (apkFilePath != null && apkFilePath.length() > 0) {
//                                CoocaaApplication.CoocaaVersion cv = null;
//                                try {
//                                    cv = CoocaaApplication.getCoocaaVersion();
//                                    if (cv.major >= 5)
//                                        installWithAutoInstaller(apkFilePath);
//                                    else
//                                        installWithPackageInstaller(apkFilePath);
//                                } catch (Exception e) {
//                                    installWithPackageInstaller(apkFilePath);
//                                }
//                            }
//                        }
//                    });
//                }
//                boolean can_show_loading = Boolean.valueOf(params.params.get("can_show_loading"));
//                if (can_show_dialog && can_show_loading)
//                    upgradeDialog.show();
//            }
//        });

        String device_channel = params.params.get("device_channel");
        _getUpgradeInfo(device_channel);
    }

    @Override
    public String exec(String cmd, UpgradeParams params) {
        LogUtils.d("upgrade", "cmd:" + cmd);
        if (cmd.equals("enable_dialog"))
            can_show_dialog = true;
        else if (cmd.equals("disable_dialog"))
            can_show_dialog = false;
        return "";
    }

    @Override
    public String getDownloadUrl() {
        return url;
    }

    @Override
    public UpgradeInfo getUpgradeInfo() {
        return info;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onProgress(int percent, long downloaded_length, long file_length) {
        super.onProgress(percent, downloaded_length, file_length);
    }

    @Override
    public void onError(String e) {
        super.onError(e);
    }

    @Override
    public void onSuccess(File f) {
        super.onSuccess(f);
    }

    @Override
    public void onCancel() {
        super.onCancel();
    }

    @Override
    public void onUpdateFilePrepared(final String path) {
        super.onUpdateFilePrepared(path);
        LiteHandlerThread.postOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (can_show_dialog) {
                    if (upgradeDialog == null) {
                        upgradeDialog = new UpgradeDialog(mContext);
                        upgradeDialog.setOnUpdateEventListener(new UpgradeDialog.OnUpgradeDialogEventListener() {
                            @Override
                            public void onClickCallBack(String apkFilePath) {
                                if (apkFilePath != null && apkFilePath.length() > 0) {
                                    CoocaaApplication.CoocaaVersion cv = null;
                                    try {
                                        try {
                                            Runtime.getRuntime().exec("chmod -R 755 " + apkFilePath);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                        File f = new File(apkFilePath);
                                        try {
                                            if (f.exists()) {
                                                LogUtils.d("upgrade", " set file r w e  ");
                                                f.setReadable(true, false);
                                                f.setWritable(true, false);
                                                f.setExecutable(true, false);
                                            }
                                        } catch (Exception e1) {
                                            LogUtils.d("upgrade", " set  error!!!!!!!!!");
                                            e1.printStackTrace();
                                        }
                                        cv = CoocaaApplication.getCoocaaVersion();
                                        if (cv.major >= 5)
                                            installWithAutoInstaller(apkFilePath);
                                        else
                                            installWithPackageInstaller(apkFilePath);
                                    } catch (Exception e) {
                                        installWithPackageInstaller(apkFilePath);
                                    }
                                }
                            }
                        });
                    }
                    upgradeDialog.show();
                    upgradeDialog.refreshUpdateMsg(info.upgradeLog, path);
                }
            }
        });
    }

    @Override
    public void onUpdateFileNotExist() {
        super.onUpdateFileNotExist();
        LiteHandlerThread.postOnUiThread(new Runnable() {
                                             @Override
                                             public void run() {

                                                 if (can_show_dialog && show_dialog_type == SHOW_DIALOG_TYPE_ALL) {
                                                     TipToast.getInstance(mContext).showTipToast(mContext.getResources().getString(R.string.toast_upgrade_no_upgradeinfo));
//                                                     
//                                                     upgradeDialog.show();
//                                                     upgradeDialog.refreshUpdateMsg("無升級信息", "");
                                                 }
                                             }
                                         }

        );
    }

    private int getApkPreferInstallLocation(String file) {
        int installlocation = 0;
        try {
            PackageParser.PackageLite pkg = null;
            if (Build.VERSION.SDK_INT < 21) {
                Method staticMethod = PackageParser.class.getDeclaredMethod("parsePackageLite",
                        new Class[]{String.class, int.class});
                pkg = (PackageParser.PackageLite) staticMethod.invoke(null, new Object[]{
                        file, 0});
            } else {
                Method staticMethod = PackageParser.class.getDeclaredMethod("parsePackageLite",
                        new Class[]{File.class, int.class});
                pkg = (PackageParser.PackageLite) staticMethod.invoke(null, new Object[]{
                        new File(file), 0});
            }
            if (pkg != null)
                installlocation = pkg.installLocation;
            Runtime.getRuntime().gc();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return installlocation;
    }

    private static final int INSTALL_LOCATION_UNSPECIFIED = -1;
    private static final int INSTALL_LOCATION_AUTO = 0;
    private static final int INSTALL_LOCATION_INTERNAL_ONLY = 1;
    private static final int INSTALL_LOCATION_PREFER_EXTERNAL = 2;

    private void installWithPackageInstaller(String apkfile) {
        try {
            Uri uri = Uri.fromFile(new File(apkfile));
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("SKYWORTH_HIDE_FLAG_PACKAGENAME", mContext.getPackageName());

            int preferlocation = getApkPreferInstallLocation(apkfile);
            LogUtils.d("HHHH", "preferlocation:" + preferlocation);
            switch (preferlocation) {
                case INSTALL_LOCATION_INTERNAL_ONLY:
                    intent.putExtra("APP_INSTALL_LOCATION", 1);
                    break;
                case INSTALL_LOCATION_PREFER_EXTERNAL:
                case INSTALL_LOCATION_AUTO:
                case INSTALL_LOCATION_UNSPECIFIED:
                    if (SdCardChecker.isSDCardAvaiable()) {
                        intent.putExtra("APP_INSTALL_LOCATION", 2);
                    } else {
                        intent.putExtra("APP_INSTALL_LOCATION", 0);
                    }
                    break;
            }
            mContext.startActivity(intent);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void installWithAutoInstaller(String apkfile) {
        try {
            Intent intent = new Intent("coocaa.intent.action.AUTOINSTALLER");
            intent.putExtra("apkfilepath", apkfile);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
        } catch (Exception e) {
            installWithPackageInstaller(apkfile);
        }
    }
}
